<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>角色管理</span>
                <el-button type="primary" @click="showAddDialog">添加角色</el-button>
            </div>
        </template>

        <!-- 角色列表 -->
        <el-table :data="roleList" style="width: 100%">
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="roleDesc" label="角色描述" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑角色对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
            <el-form :model="roleForm" :rules="rules" ref="roleFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="roleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input type="textarea" v-model="roleForm.roleDesc"></el-input>
                </el-form-item>
                <el-form-item label="权限设置">
                    <el-tree
                        ref="permissionTree"
                        :data="permissionList"
                        show-checkbox
                        node-key="id"
                        :default-checked-keys="checkedPermissions"
                        :props="defaultProps">
                    </el-tree>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    getRoleListService,
    addRoleService,
    updateRoleService,
    deleteRoleService,
    getRolePermissionsService,
    updateRolePermissionsService
} from '@/api/role.js'

// 角色列表数据
const roleList = ref([])

// 权限树数据
const permissionList = ref([
    {
        id: 1,
        label: '系统管理',
        children: [
            { id: 11, label: '用户管理' },
            { id: 12, label: '角色管理' },
            { id: 13, label: '权限管理' }
        ]
    },
    {
        id: 2,
        label: '内容管理',
        children: [
            { id: 21, label: '栏目管理' },
            { id: 22, label: '文章管理' }
        ]
    },
    {
        id: 3,
        label: '审计管理',
        children: [
            { id: 31, label: '操作日志' },
            { id: 32, label: '登录日志' }
        ]
    }
])

const defaultProps = {
    children: 'children',
    label: 'label'
}

// 表单数据
const roleForm = ref({
    roleName: '',
    roleDesc: ''
})

// 表单验证规则
const rules = {
    roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    roleDesc: [
        { required: true, message: '请输入角色描述', trigger: 'blur' }
    ]
}

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentRoleId = ref(null)
const checkedPermissions = ref([])

// 获取角色列表
const getRoleList = async () => {
    try {
        const res = await getRoleListService()
        roleList.value = res.data
    } catch (error) {
        ElMessage.error('获取角色列表失败')
    }
}

// 显示添加对话框
const showAddDialog = () => {
    dialogTitle.value = '添加角色'
    isEdit.value = false
    roleForm.value = {
        roleName: '',
        roleDesc: ''
    }
    checkedPermissions.value = []
    dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
    dialogTitle.value = '编辑角色'
    isEdit.value = true
    currentRoleId.value = row.id
    roleForm.value = {
        roleName: row.roleName,
        roleDesc: row.roleDesc
    }
    
    // 获取角色权限
    try {
        const res = await getRolePermissionsService(row.id)
        checkedPermissions.value = res.data
    } catch (error) {
        ElMessage.error('获取角色权限失败')
    }
    
    dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
    try {
        const permissionTree = ref(null)
        const selectedPermissions = permissionTree.value.getCheckedKeys()
        
        if (isEdit.value) {
            await updateRoleService({
                id: currentRoleId.value,
                ...roleForm.value
            })
            await updateRolePermissionsService(currentRoleId.value, selectedPermissions)
            ElMessage.success('更新角色成功')
        } else {
            await addRoleService(roleForm.value)
            ElMessage.success('添加角色成功')
        }
        
        dialogVisible.value = false
        getRoleList()
    } catch (error) {
        ElMessage.error(isEdit.value ? '更新角色失败' : '添加角色失败')
    }
}

// 删除角色
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该角色？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteRoleService(row.id)
            ElMessage.success('删除成功')
            getRoleList()
        } catch (error) {
            ElMessage.error('删除失败')
        }
    })
}

onMounted(() => {
    getRoleList()
})
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}
</style> 